/**
 *
 */
package anysware.gwt.client.rest;

import anysware.gwt.client.util.PageUtils;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;

/**
 * TODO: doc me
 *
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 110 $
 * @version
 */
public class RestRequestBuilder extends RequestBuilder {
	public static RestRequestBuilder createBuilder(final String httpMethod,
	        final String url) {
		final String realMethodName = getRealMethod(httpMethod);
		final RestRequestBuilder builder = new RestRequestBuilder(
		        realMethodName, url);
		if (!realMethodName.equals(httpMethod)) {
			builder.setHeader("X-Http-Method", httpMethod);
		}
		return builder;
	}

	private static String getRealMethod(final String methodName) {
		final String agent = PageUtils.getProperty("agent");
		if (agent.indexOf("webkit") != -1) {
			if (!methodName.equals("POST") || !methodName.equals("GET")) {
				return "POST";
			}
		}
		return methodName;
	}

	private RestRequestBuilder(final String httpMethod, final String url) {
		super(httpMethod, url);
	}

	public void sendRequest(final String requestData,
	        final CallbackListener listener) {
		try {
			super.sendRequest(requestData, new RequestCallback() {
				public void onError(final Request request,
				        final Throwable exception) {
					listener
					        .handle(new CallbackEvent(this, request, exception));
				}
				public void onResponseReceived(final Request request,
				        final Response response) {
					listener.handle(new CallbackEvent(this, request, response));
				}
			});
		} catch (final RequestException e) {
			listener.handle(new CallbackEvent(this, e));
		}
	}

}
